import os
import subprocess
import wx


class InstallApkApp(wx.Frame):
    def __init__(self, *args, **kw):
        super(InstallApkApp, self).__init__(*args, **kw)

        self.SetTitle("APK Installer")
        self.SetMinSize((600, 400))
        # self.Centre()

        panel = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)

        # Folder selection section
        self.folder_path = ""
        default_folder_path = read_default_folder_path()
        if default_folder_path is not None:
            self.folder_path = default_folder_path
        folder_label = wx.StaticText(panel, label="Select APK Folder:")
        self.folder_text = wx.TextCtrl(panel, value="", size=(400, -1), style=wx.TE_READONLY)
        browse_button = wx.Button(panel, label="Browse")

        browse_button.Bind(wx.EVT_BUTTON, self.on_browse_folder)

        folder_box = wx.BoxSizer(wx.HORIZONTAL)
        folder_box.Add(folder_label, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
        folder_box.Add(self.folder_text, 1, wx.EXPAND | wx.ALL, 5)
        folder_box.Add(browse_button, 0, wx.ALL, 5)

        # APK list section
        self.apk_listbox = wx.ListBox(panel, choices=[], size=(580, 200))
        refresh_apk_button = wx.Button(panel, label="Refresh APK List")

        refresh_apk_button.Bind(wx.EVT_BUTTON, self.refresh_apk_list)

        apk_box = wx.BoxSizer(wx.VERTICAL)
        apk_box.Add(self.apk_listbox, 1, wx.EXPAND | wx.ALL, 5)
        apk_box.Add(refresh_apk_button, 0, wx.ALL | wx.CENTER, 5)

        # Install button
        install_box = wx.BoxSizer(wx.HORIZONTAL)
        install_button_selected = wx.Button(panel, label="Install Selected APKs")
        install_button_selected.Bind(wx.EVT_BUTTON, self.install_selected_apks)
        install_button_all = wx.Button(panel, label="Install All APKs")
        install_button_all.Bind(wx.EVT_BUTTON, self.install_selected_all_apks)
        install_box.Add(install_button_selected, 1, wx.EXPAND | wx.ALL, 5)
        install_box.Add(install_button_all, 1, wx.EXPAND | wx.ALL, 5)

        # Layout
        vbox.Add(folder_box, 0, wx.EXPAND | wx.ALL, 10)
        vbox.Add(apk_box, 1, wx.EXPAND | wx.ALL, 10)
        vbox.Add(install_box, 0, wx.EXPAND | wx.ALL, 10)

        panel.SetSizer(vbox)

        new_font_size = 10
        for child in panel.GetChildren():
            if isinstance(child, (wx.StaticText, wx.TextCtrl, wx.Button, wx.ListBox)):
                font = child.GetFont()
                font.SetPointSize(new_font_size)
                child.SetFont(font)

        if self.folder_path is not None and self.folder_path != "":
            self.folder_text.SetValue(self.folder_path)
            self.refresh_apk_list(event=None)

    def on_browse_folder(self, event):
        dialog = wx.DirDialog(None, "Choose a directory", self.folder_path, wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST)
        if dialog.ShowModal() == wx.ID_OK:
            self.folder_path = dialog.GetPath()
            self.folder_text.SetValue(self.folder_path)
            self.refresh_apk_list(event=None)
        dialog.Destroy()

    def refresh_apk_list(self, event):
        self.apk_listbox.Clear()
        if not self.folder_path:
            return
        for filename in os.listdir(self.folder_path):
            if filename.lower().endswith(".apk"):
                self.apk_listbox.Append(filename)

    def install_selected_apks(self, event):
        selected_indices = self.apk_listbox.GetSelections()
        if not selected_indices:
            wx.MessageBox("No APK files selected.", "Error", wx.OK | wx.ICON_ERROR)
            return

        for index in selected_indices:
            apk_name = self.apk_listbox.GetString(index)
            apk_path = os.path.join(self.folder_path, apk_name)
            try:
                result = subprocess.run(["adb", "install", apk_path], capture_output=True, text=True)
                if result.returncode == 0:
                    wx.MessageBox(f"Installed {apk_name} successfully.\n{result.stdout}", "Success",
                                  wx.OK | wx.ICON_INFORMATION)
                else:
                    wx.MessageBox(f"Failed to install {apk_name}:\n{result.stderr}", "Error", wx.OK | wx.ICON_ERROR)
            except Exception as e:
                wx.MessageBox(f"An error occurred while installing {apk_name}:\n{str(e)}", "Error",
                              wx.OK | wx.ICON_ERROR)

    def install_selected_all_apks(self, event):
        all_apks = self.apk_listbox.GetStrings()
        if not all_apks:
            wx.MessageBox("No APK file.", "Error", wx.OK | wx.ICON_ERROR)
            return

        for apk_name in all_apks:
            apk_path = os.path.join(self.folder_path, apk_name)
            try:
                result = subprocess.run(["adb", "install", apk_path], capture_output=True, text=True)
                if result.returncode == 0:
                    wx.MessageBox(f"Installed {apk_name} successfully.\n{result.stdout}", "Success",
                                  wx.OK | wx.ICON_INFORMATION)
                else:
                    wx.MessageBox(f"Failed to install {apk_name}:\n{result.stderr}", "Error", wx.OK | wx.ICON_ERROR)
                    if result.stderr.startswith("adb.exe: no devices"):
                        return
            except Exception as e:
                wx.MessageBox(f"An error occurred while installing {apk_name}:\n{str(e)}", "Error",
                              wx.OK | wx.ICON_ERROR)


def read_default_folder_path():
    if os.path.isfile("default_file_path.txt"):
        with open("default_file_path.txt", 'r', encoding='utf-8') as file:
            for line in file:
                stripped_line = line.strip()
                if stripped_line:
                    return stripped_line
    else:
        file = open("default_file_path.txt", "w")
        file.close()


if __name__ == "__main__":
    app = wx.App(False)
    frame = InstallApkApp(None)
    frame.Show(True)
    app.MainLoop()
